package com.tegtech.tools.aliyun.support;

import java.util.Map;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials;
import com.google.common.collect.Maps;
import com.tegtech.tools.aliyun.properties.AliyunProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取STS临时授权
 * @Author Jun
 * @date 2021年4月27日 下午4:18:16
 */
@Slf4j
public class AssumeRole {

	private static final long EXPIRE = 3600L; // The Min/Max value of DurationSeconds is 15min/1hr
	
	/**
	 * 获取sts临时权限
	 * @return
	 */
	public static Map<String, String> stsRole() {
		Map<String, String> map = Maps.newHashMap();
		DefaultAcsClient client = null;
		try {
			//构造default profile（参数留空，无需添加Region ID）
            IClientProfile profile = DefaultProfile.getProfile("", AliyunProperties.getAccessId(), AliyunProperties.getAccessSecret());
            //用profile构造client
            client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysEndpoint(AliyunProperties.getStsEndpoint());
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(AliyunProperties.getStsRoleArn());
            request.setRoleSessionName("session-ram");
            request.setDurationSeconds(EXPIRE); // 设置凭证有效时间
            final AssumeRoleResponse response = client.getAcsResponse(request);
            Credentials credentials = response.getCredentials();
            map.put("Expiration", credentials.getExpiration());
            map.put("AccessKeyId", credentials.getAccessKeyId());
            map.put("AccessKeySecret", credentials.getAccessKeySecret());
            map.put("SecurityToken", credentials.getSecurityToken());
            map.put("endPoint", AliyunProperties.getOssEndpoint());
            map.put("bucketName", AliyunProperties.getOssBucket());
            map.put("host", AliyunProperties.getOssHost());
        } catch (ClientException e) {
            log.error("获取阿里云STS权限出错，错误码：{}，错误信息：{}", e.getErrCode(), e.getErrMsg());
        } finally {
        	if(client != null) {
        		client.shutdown();
        	}
		}
		return map;
	}
	
}
